/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.course.service.impl;

import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.service.BaseCommonService;
import com.fanrenqiji.entity.*;
import com.fanrenqiji.modules.business.course.dao.CourseDao;
import com.fanrenqiji.modules.business.course.service.CourseService;
import com.fanrenqiji.modules.business.course.vo.CoursePageVO;
import com.fanrenqiji.modules.business.course.vo.CourseVO;
import com.fanrenqiji.modules.business.event.dao.EventDao;
import com.fanrenqiji.modules.business.event.vo.EventVO;
import com.fanrenqiji.modules.business.eventcase.dao.EventCaseDao;
import com.fanrenqiji.modules.business.eventcase.vo.EventCaseVO;
import com.fanrenqiji.modules.business.teacher.dao.TeacherDao;
import com.fanrenqiji.modules.business.teacher.vo.TeacherVO;
import com.fanrenqiji.modules.sys.dao.ConfigDao;
import com.fanrenqiji.modules.sys.entity.Config;
import com.fanrenqiji.modules.sys.entity.Role;
import com.fanrenqiji.modules.sys.entity.User;
import com.fanrenqiji.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 课程信息业务逻辑实现
 *
 * @author wentao
 */
@Service(value = "course")
@Transactional(readOnly = true)
public class CourseServiceImpl  extends BaseCommonService implements CourseService {

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private ConfigDao configDao;
    @Autowired
    private EventDao eventDao;
    @Autowired
    private EventCaseDao eventCaseDao;
    @Autowired
    DozerBeanMapper beanMapper;

    /**
     * 插入
     *
     * @param course 插入的对象
     * @return 插入数据条数
     */
    @Transactional
    public CourseVO insert(CourseVO course) {
        CourseEntity courseEntity = new CourseEntity();
        beanMapper.map(course, courseEntity);
        courseDao.save(courseEntity);
        beanMapper.map(courseEntity, course);
        return course;
    }


    /**
     * 批量插入
     *
     * @param list 数据列表
     * @return 插入数据条数
     */
    @Transactional
    public void insertList(List<CourseVO> list) {
        for (CourseVO course : list) {
            insert(course);
        }
    }


    /**
     * 修改
     *
     * @param course 修改的数据
     * @return 修改的数据
     */
    @Transactional
    public CourseVO update(CourseVO course, String knowledgersid[], String gradeids[]) {
        CourseEntity courseEntity = null;
        if (StringUtils.isNotEmpty(course.getId())) {
            courseEntity = courseDao.findOne(Long.parseLong(course.getId()));
        }
        if (courseEntity == null) {
            courseEntity = new CourseEntity();

        }


        // 将代理对象  装换成实体
        if (course.getTeacher() != null) {
            if (StringUtils.isNoneBlank(course.getTeacher().getId())) {
                TeacherEntity teacherEntity = teacherDao.findOne(Long.parseLong(course.getTeacher().getId()));
                TeacherVO teacherVO = new TeacherVO();
                beanMapper.map(teacherEntity, teacherVO);
                course.setTeacher(teacherVO);
                courseEntity.setTeacher(teacherEntity);
            } else {
                course.setTeacher(null);
                courseEntity.setTeacher(null);
            }
        }
        beanMapper.map(course, courseEntity);
        courseEntity = courseDao.save(courseEntity);
        if (StringUtils.isEmpty(course.getId())) {
            Map<String, String> configMap = Maps.newHashMap();
            for (Config config : configDao.findConfigByItem("DEFAULT_COURSE_ITEM")) {
                configMap.put(config.getName(), config.getValue());
            }

            beanMapper.map(courseEntity, course);
            return course;
        }
            return   null;
    }
    /**
     * 删除
     *
     * @param id 数据标识
     * @return 删除的数据条数
     */
    @Transactional
    public void delete(String id) {
        courseDao.deleteById(Long.parseLong(id));
    }


    /**
     * 查询所有数据
     *
     * @return 数据列表
     */
    public List<CourseVO> getAll() {
        List<CourseVO> list = Lists.newArrayList();
        List<CourseEntity> entities = courseDao.findAllList();
        for (CourseEntity courseEntity : entities) {
            CourseVO courseVO = new CourseVO();
            beanMapper.map(courseEntity, courseVO);
            list.add(courseVO);
        }
        return list;
    }


    /**
     * 通过条件查询数据列表
     *
     * @param course 查询条件
     * @return 数据列表
     */
    public List<CourseVO> getList(CourseVO course) {
        List<CourseVO> list = Lists.newArrayList();
        DetachedCriteria dc = courseDao.createDetachedCriteria();
        dc.add(Restrictions.eq(CourseEntity.DEL_FLAG, CourseEntity.DEL_FLAG_NORMAL));
    /*
    dc.createAlias("course", "course"); // as

    dc.add(Restrictions.ne("id", 1L)); // !=

    if (StringUtils.isNotEmpty(course.getName())) {
        dc.add(Restrictions.like("name", "%" + course.getName() + "%")); //like
    }
    if (StringUtils.isNotEmpty(course.getName())) {
        dc.add(Restrictions.eq("name", course.getName()));
    }

	dc.addOrder(Order.asc("office.id")).addOrder(Order.asc("name"));

    */
        List<CourseEntity> entities = courseDao.find(dc);
        for (CourseEntity courseEntity : entities) {
            CourseVO courseVO = new CourseVO();
            beanMapper.map(courseEntity, courseVO);
            list.add(courseVO);
        }
        return list;
    }


    /**
     * 通过id查询数据
     *
     * @param id 数据标识
     * @return 数据对象
     */
    public CourseVO get(String id) {
        CourseVO course = new CourseVO();
        CourseEntity courseEntity = courseDao.findOne(Long.parseLong(id));
        if (courseEntity == null) {
            courseEntity = new CourseEntity();
        }
        beanMapper.map(courseEntity, course);
        return course;
    }

    /**
     * 根据条件分页查询
     *
     * @param page
     * @param course
     * @return
     */
    public Page<CoursePageVO> findCourseByPage(Page<CoursePageVO> page, CoursePageVO course) {
        Page<CourseEntity> pageEntity = new Page<CourseEntity>(page.getPageNo(), page.getPageSize());
        DetachedCriteria dc = courseDao.createDetachedCriteria();
        dc.add(Restrictions.eq(CourseEntity.DEL_FLAG, CourseEntity.DEL_FLAG_NORMAL));
        dc.addOrder(Order.desc("id"));
        // 如果tile 不为空 根据title来进行查询
        if (StringUtils.isNotBlank(course.getTitle())) {
            dc.add(Restrictions.like("title", course.getTitle(), MatchMode.ANYWHERE));
        }
        // 如果学科id不为空 那么就根据学科来进行搜索
        // 还可以根据主讲老师id 来进行查询
        if (course.getTeacher() != null) {
            if (StringUtils.isNotBlank(course.getTeacher().getId())) {
                dc.add(Restrictions.eq("teacher.id", Long.parseLong(course.getTeacher().getId())));
            }
        }
        // 还可以根据是否免费来进行查询
        if (StringUtils.isNotBlank(course.getFree())) {
            dc.add(Restrictions.eq("free", Integer.parseInt(course.getFree())));
        }
    /*
    dc.createAlias("course", "course"); // as

    dc.add(Restrictions.ne("id", 1L)); // !=

    if (StringUtils.isNotEmpty(course.getName())) {
        dc.add(Restrictions.like("name", "%" + course.getName() + "%")); //like
    }
    if (StringUtils.isNotEmpty(course.getName())) {
        dc.add(Restrictions.eq("name", course.getName()));
    }

    if (!StringUtils.isNotEmpty(page.getOrderBy())) {
	    dc.addOrder(Order.asc("name"))
		  .addOrder(Order.desc("id"));
	}
    */
        User user = UserUtils.getUser();
        boolean isDataScopeAll = false;
        List<String> dataScope = Lists.newArrayList();
        for (Role r : user.getRoleList()) {
            if (!dataScope.contains(r.getDataScope())) {
                if (Role.DATA_SCOPE_SELF.equals(r.getDataScope())&&r.getPermissions().contains("business:course:view")) {
                    isDataScopeAll = true;
                    break;
                }
            }
        }
        if(isDataScopeAll){
            dc.add(Restrictions.eq("createBy", user.getName()));
        }
        pageEntity = courseDao.find(pageEntity, dc);
        beanMapper.map(pageEntity, page);
        List<CoursePageVO> list = Lists.newArrayList();
        for (CourseEntity courseEntity : pageEntity.getList()) {
            CoursePageVO courseVO = new CoursePageVO();
            beanMapper.map(courseEntity, courseVO);
            list.add(courseVO);
        }
        page.setList(list);
        return page;
    }

    /**
     * 将图片按照顺序进行保存的方法
     *
     * @param courseVO
     * @param courseitemsids
     */
    @Transactional
    public void savacourseitem(CourseVO courseVO, String courseitemsids, String courseitemsids2) {
    }


    /**
     * 查询事件id 为1的事件实例
     *
     * @return
     */
    public List<EventCaseVO> geteventcase(CourseVO courseVO) {
        ArrayList<EventCaseVO> eventCaseVOS = Lists.newArrayList();
        if (StringUtils.isNotBlank(courseVO.getId())) {
            CourseEntity courseEntity = courseDao.findOne(Long.parseLong(courseVO.getId()));
            //将实体类里面的事件实例的集合取出来
            List<EventCaseEntity> eventCases = courseEntity.getEventCases();
            // 排除事件实例里面关联的事件对象为1的事件
            // 只展示作业
            ArrayList<EventCaseEntity> eventCaseEntities = Lists.newArrayList();

            for (EventCaseEntity eventCase : eventCases) {
//                if(eventCase.getEvent().getCategory()!=3) continue;
                eventCaseEntities.add(eventCase);
            }
            // 接下来进行转化

            for (EventCaseEntity eventCaseEntity : eventCaseEntities
                    ) {
                Long id = eventCaseEntity.getEvent().getId();
              /*  if (id == 1) {*/
                EventCaseVO eventCaseVO = new EventCaseVO();
                beanMapper.map(eventCaseEntity, eventCaseVO);
                eventCaseVOS.add(eventCaseVO);
                /*}*/
            }


        }
        return eventCaseVOS;
    }

    /**
     * 查询事件id bu为1的事件实例
     *
     * @return
     */
    public List<EventCaseVO> geteventcasene(CourseVO courseVO) {
        ArrayList<EventCaseVO> eventCaseVOS = Lists.newArrayList();
        if (StringUtils.isNotBlank(courseVO.getId())) {
            CourseEntity courseEntity = courseDao.findOne(Long.parseLong(courseVO.getId()));
            //将实体类里面的事件实例的集合取出来
            List<EventCaseEntity> eventCases = courseEntity.getEventCases();
            // 排除事件实例里面关联的事件对象为1的事件
            // 接下来进行转化

            for (EventCaseEntity eventCaseEntity : eventCases
                    ) {
                Long id = eventCaseEntity.getEvent().getId();
                if (id != 1) {
                    EventCaseVO eventCaseVO = new EventCaseVO();
                    beanMapper.map(eventCaseEntity, eventCaseVO);
                    eventCaseVOS.add(eventCaseVO);
                }

            }


        }
        return eventCaseVOS;
    }

    /**
     * 这是进行校验的方法  保证每个图片的下面都有一个音频
     * @param courseitemsids
     * @return
     */
    public Integer jiaoyanyinpin(String courseitemsids){
        Integer flag = 0;

    return  flag;
    }

    /**
     * 查看当前的事件集合
     * @param courseVO
     * @return
     */
    public List<EventVO> findEventByCourse(CourseVO courseVO){
        /*CourseEntity one = courseDao.findOne(Long.parseLong(courseVO.getId()));
        List<EventEntity> eventEntities = one.getEventEntities();
        ArrayList<EventVO> eventvos = Lists.newArrayList();
        for (EventEntity eventEntity : eventEntities) {
            EventVO eventVO = new EventVO();
            beanMapper.map(eventEntity,eventVO);
            eventvos.add(eventVO);
        }
        return eventvos;*/
        return null;
    }
}
